package com.drinks.yiniang.ui.activity.user.milepost;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.user.milepost.MilepostShareAdapter;
import com.drinks.yiniang.common.help.ShareHelp;
import com.drinks.yiniang.common.recycler.decoration.FavoriteItemDecoration;
import com.drinks.yiniang.entity.common.RadarEntity;
import com.drinks.yiniang.entity.goods.GoodsJson;
import com.drinks.yiniang.entity.goods.RecommendGoodsJson;
import com.drinks.yiniang.entity.user.milepost.MilepostShareJson;
import com.drinks.yiniang.io.api.GoodsApiIO;
import com.drinks.yiniang.io.api.MilepostApiIO;
import com.drinks.yiniang.ui.activity.goods.GoodsDetailsActivity;
import com.drinks.yiniang.ui.widget.dialog.ShareDialog;
import com.drinks.yiniang.ui.widget.recycler.BaseRecyclerView;
import com.drinks.yiniang.ui.widget.view.RadarMapView;
import com.drinks.yiniang.utils.GlideUtils;
import com.drinks.yiniang.utils.RecyclerUtils;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.listener.OnNavgationBarClickListener;
import com.hansen.library.pickerimage.utils.media.ImageTools;
import com.hansen.library.ui.activity.BaseTranBarActivity;
import com.hansen.library.ui.widget.image.CircleImageView;
import com.hansen.library.ui.widget.nav.NavigationBarLayout;
import com.hansen.library.utils.ColorUtils;
import com.hansen.library.utils.CommonUtils;
import com.hansen.library.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

import lecho.lib.hellocharts.gesture.ContainerScrollType;
import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;

/**
 * 里程碑分享页面
 *
 * @author han
 * @date 2019/09/10
 */
public class MilepostShareActivity extends BaseTranBarActivity implements OnNavgationBarClickListener,
        BaseQuickAdapter.OnItemClickListener, ShareDialog.OnShareActionListener {

    //nav
    private NavigationBarLayout nav_bar_milepost_share;
    //列表
    private BaseRecyclerView rcv_milepost_share;
    //header view
    private View mShareHeaderView;
    //头像
    private CircleImageView iv_milepost_share_avatar;
    //昵称
    private TextView tv_milepost_share_nickname;
    //雷达图
    private RadarMapView chart_radar_map_milepost_share;
    //最喜爱的风格
    private TextView tv_milepost_share_style;
    private LineChartView mLineChartView;

    private MilepostShareAdapter mMilepostShareAdapter;

    private ShareHelp mShareHelp;

    @Override
    protected void initView() {
        nav_bar_milepost_share = findViewById(R.id.nav_bar_milepost_share);

        rcv_milepost_share = findViewById(R.id.rcv_milepost_share);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mContext = this;

        initAdapter();
        getMilepostShareData();
        getRecommend();
    }

    private void initAdapter() {
        rcv_milepost_share.setLayoutManager(RecyclerUtils.getVerticalGridLayout(mContext, 2));
        rcv_milepost_share.addItemDecoration(FavoriteItemDecoration.getItemDPDecoration(10));

        mMilepostShareAdapter = new MilepostShareAdapter(mContext, new ArrayList<GoodsJson.GoodsList>());
        mMilepostShareAdapter.addHeaderView(getHeaderView());
        mMilepostShareAdapter.addHeaderView(getHeaderTitleView());
        mMilepostShareAdapter.setHeaderAndEmpty(true);
        mMilepostShareAdapter.setCommonEmpty(getLayoutInflater(), rcv_milepost_share);
        mMilepostShareAdapter.bindToRecyclerView(rcv_milepost_share);
    }

    //获取header
    private View getHeaderView() {
        mShareHeaderView = getLayoutInflater().inflate(R.layout.header_milepost_share, (ViewGroup) rcv_milepost_share.getParent(), false);

        iv_milepost_share_avatar = mShareHeaderView.findViewById(R.id.iv_milepost_share_avatar);

        tv_milepost_share_nickname = mShareHeaderView.findViewById(R.id.tv_milepost_share_nickname);
        tv_milepost_share_style = mShareHeaderView.findViewById(R.id.tv_milepost_share_style);

        chart_radar_map_milepost_share = mShareHeaderView.findViewById(R.id.chart_radar_map_milepost_share);

        mLineChartView = mShareHeaderView.findViewById(R.id.chart_milepost_share_category);

        return mShareHeaderView;
    }

    //获取header
    private View getHeaderTitleView() {
        View mHeaderView = getLayoutInflater().inflate(R.layout.header_common_title, (ViewGroup) rcv_milepost_share.getParent(), false);

        TextView tvTitle = mHeaderView.findViewById(R.id.tv_header_common_title);

        tvTitle.setText(R.string.text_recommend_goods_dot);

        return mHeaderView;
    }

    @Override
    protected void initListener() {
        nav_bar_milepost_share.setOnNavgationBarClickListener(this);
        mMilepostShareAdapter.setOnItemClickListener(this);
    }

    @Override
    public void widgetClick(View v) {

    }

    @Override
    public int getTranBarResID() {
        return R.layout.activity_milepost_share;
    }

    @Override
    public void onBackClick(View v) {
        finish();
    }

    @Override
    public void onEditClick(View v) {
        //分享
        ShareDialog dialog = ShareDialog.newInstance();

        dialog.show(getSupportFragmentManager(), Constants.TAG_SHARE_DIALOG);
    }

    @Override
    public void onShare(int shareType) {
        if(mShareHelp == null) {
            mShareHelp = new ShareHelp(this);
        }
        switch (shareType) {
            case ShareDialog.SHARE_WX_FRIENDS:
                mShareHelp.wxShareBitmap(true, ImageTools.createViewBitmap(mShareHeaderView));
                break;
            case ShareDialog.SHARE_WX_MOMENTS:
                mShareHelp.wxShareBitmap(false, ImageTools.createViewBitmap(mShareHeaderView));
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        GoodsJson.GoodsList data = mMilepostShareAdapter.getItem(position);

        if (data == null) {
            return;
        }

        Intent intent = new Intent(mContext, GoodsDetailsActivity.class);
        intent.putExtra(Constants.KeyGoodsId, data.getId());
        startActivity(intent);
    }

    //获取推荐列表
    private void getRecommend() {
        GoodsApiIO.getInstance().getRecommendGoodsList(new APIRequestCallback<RecommendGoodsJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(RecommendGoodsJson res) {
                if (mMilepostShareAdapter == null) {
                    return;
                }

                mMilepostShareAdapter.getData().clear();
                mMilepostShareAdapter.addData(res.getData());
                mMilepostShareAdapter.loadMoreEnd();
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                mMilepostShareAdapter.loadMoreFail();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    //获取里程碑分享数据
    private void getMilepostShareData() {
        showLoadingDialog();

        MilepostApiIO.getInstance().getMilepostShareData(new APIRequestCallback<MilepostShareJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(MilepostShareJson res) {
                setData(res.getData());
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    private void setData(MilepostShareJson.MilepostShareData data) {
        //头像
        GlideUtils.loadAvatar(mContext, iv_milepost_share_avatar, data.getAvatar());
        //昵称
        tv_milepost_share_nickname.setText(data.getUsername());
        //最喜爱的风格
        tv_milepost_share_style.setText(String.format(getString(R.string.text_favorite_style_format), data.getLike_style()));

        int size = CommonUtils.getListSize(data.getCategory_arr());

        chart_radar_map_milepost_share.setVisibility(size >= 5 ? View.VISIBLE : View.GONE);

        if (size >= 5) {
            List<RadarEntity> radarList = new ArrayList<>();

            for (MilepostShareJson.MilepostRadar radarData : data.getCategory_arr()) {
                radarList.add(new RadarEntity(radarData.getCategory_name(), StringUtils.getInt(radarData.getTotal())));
            }

            chart_radar_map_milepost_share.setRadarData(radarList);
        }

        initLineChart(data.getLine());
    }

    private void initLineChart(List<MilepostShareJson.MilepostChart> lineDataList) {
        if (CommonUtils.isEmptyList(lineDataList)) {
            return;
        }

        List<PointValue> mPointValues = new ArrayList<>();
        List<AxisValue> mAxisXValues = new ArrayList<>();

        MilepostShareJson.MilepostChart lineData;

        for (int i = 0; i < lineDataList.size(); i++) {
            lineData = lineDataList.get(i);
            mAxisXValues.add(new AxisValue(i).setLabel(lineData.getLabel()));
            mPointValues.add(new PointValue(i, StringUtils.getFloat(lineData.getValue())));

        }

        Line line = new Line(mPointValues).setColor(ColorUtils.getColorById(mContext, R.color.color_ef3024));  //折线的颜色（橙色）
        List<Line> lines = new ArrayList<>();
        line.setShape(ValueShape.CIRCLE);//折线图上每个数据点的形状  这里是圆形 （有三种 ：ValueShape.SQUARE  ValueShape.CIRCLE  ValueShape.DIAMOND）
        line.setCubic(false);//曲线是否平滑，即是曲线还是折线
        line.setFilled(true);//是否填充曲线的面积
        line.setHasLabels(true);//曲线的数据坐标是否加上备注
        line.setHasLabelsOnlyForSelected(true);//点击数据坐标提示数据（设置了这个line.setHasLabels(true);就无效）
        line.setHasLines(true);//是否用线显示。如果为false 则没有曲线只有点显示
        line.setHasPoints(false);//是否显示圆点 如果为false 则没有原点只有点显示（每个数据点都是个大的圆点）
        line.setStrokeWidth(2);
        lines.add(line);
        LineChartData data = new LineChartData();
        data.setLines(lines);

        //坐标轴
        Axis axisX = new Axis(); //X轴
        axisX.setHasTiltedLabels(false);  //X坐标轴字体是斜的显示还是直的，true是斜的显示
        axisX.setTextColor(ColorUtils.getColorById(mContext, R.color.color_282829));  //设置字体颜色
        axisX.setName("时间");  //表格名称
        axisX.setTextSize(10);//设置字体大小
        //axisX.setHasSeparationLine(true);
        axisX.setMaxLabelChars(0); //最多几个X轴坐标，意思就是你的缩放让X轴上数据的个数7<=x<=mAxisXValues.length
        axisX.setValues(mAxisXValues);  //填充X轴的坐标名称
        axisX.setHasLines(true); //x 轴分割线
        axisX.setHasFixedLineHeight(true);
        data.setAxisXBottom(axisX); //x 轴在底部
        //data.setAxisXTop(axisX);  //x 轴在顶部


        // Y轴是根据数据的大小自动设置Y轴上限(在下面我会给出固定Y轴数据个数的解决方案)
        Axis axisY = new Axis();  //Y轴
        axisY.setTextColor(ColorUtils.getColorById(mContext, R.color.color_282829));  //设置字体颜色
        axisY.setName("瓶数");//y轴标注
        axisY.setTextSize(10);//设置字体大小
        axisY.setHasLines(true);
        axisY.setLineColor(ColorUtils.getColorById(mContext, R.color.color_line));
        data.setAxisYLeft(axisY);  //Y轴设置在左边
        //data.setAxisYRight(axisY);  //y轴设置在右边


        //设置行为属性，支持缩放、滑动以及平移
        mLineChartView.setInteractive(true);
        mLineChartView.setZoomType(ZoomType.HORIZONTAL);
        mLineChartView.setZoomEnabled(false);
        mLineChartView.setScrollEnabled(true);
        mLineChartView.setMaxZoom(4f);//最大方法比例
        mLineChartView.setContainerScrollEnabled(true, ContainerScrollType.HORIZONTAL);
        mLineChartView.setLineChartData(data);
        mLineChartView.setVisibility(View.VISIBLE);
        /**注：下面的7，10只是代表一个数字去类比而已
         * 当时是为了解决X轴固定数据个数。见（http://forum.xda-developers.com/tools/programming/library-hellocharts-charting-library-t2904456/page2）;
         */
        Viewport v = new Viewport(mLineChartView.getMaximumViewport());
        mLineChartView.setMaximumViewport(v);
        v.left = mAxisXValues.size() - 10;
        v.right = mAxisXValues.size() - 1;
        mLineChartView.setCurrentViewport(v);
    }
}
